﻿using Caliburn.Micro;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace UrTransPayloadWpf
{
    public class ScreenEx : Screen
    {
        public class AppWindowManager : WindowManager
        {
            #region Overrides of WindowManager

            protected override Window EnsureWindow(object model, object view, bool isDialog)
            {
                var ss = view.GetType().GetProperties(BindingFlags.Static | BindingFlags.Public);
                var prop = ss.FirstOrDefault(s => s.Name == "Instance");
                if (null == prop)
                {
                    return base.EnsureWindow(model, view, isDialog);
                }
                var win = prop.GetValue(view);
                var temp = win as Window;
                if (temp != null)
                {
                    temp.Closing += (s, e) =>
                    {
                        temp.Owner?.Focus();
                    };
                    if (temp.WindowState == WindowState.Minimized)
                    {
                        temp.WindowState = WindowState.Normal;
                    }
                    temp.Focus();
                    return temp;
                }
                return base.EnsureWindow(model, win, isDialog);
            }

            #endregion
        }
        public ScreenEx()
        {
            WindowManager = new AppWindowManager();
        }
        protected IWindowManager WindowManager { get; set; }

        public void RunByException(System.Action action, string otherMsg = null)
        {
            try
            {
                if (action != null)
                {
                    action();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(otherMsg + " : " + ex.Message);
                //ExceptionMsg(otherMsg, ErrLevel.Warn, ex);
            }
        }
    }
}
